# !/usr/bin/python
# -*-coding: utf-8-*-
# Filename: Socket_Server.py

import socket


# 超时
CONNECT_TIMEOUT = 2
# 最大读取字节数
RECV_MAXSIZE = 1024


def Socket_Recv( ConnectSocket, ConnectAddr, File ) :
	'''Socket读取函数 循环处理有阻塞 故通常新建线程来执行

	   参数 ConnecSocker : socket句柄
	        ConnectAddr  : 连接端地址
	        File         : Log文件句柄 None则不写入'''

	# 信息读取循环
	while True :
		try :
			# 超时设定
			# ConnectSocket.settimeout( CONNECT_TIMEOUT )
			# 读取 等待数据状态
			buf = ConnectSocket.recv( RECV_MAXSIZE ).decode('utf-8')

			if buf == 'REMOTE_EXIT' :
				# 客户端退出
				print( 'Client Leave!' )
				break

			if buf == '' :
				# 客户端退出
				print( 'Client Leave!' )
				break

		except socket.error:
			print( 'Client Leave!' )
			break

		except socket.timeout :
			print( 'TimeOut' )
			break

		except :
			print( 'Unknown exception' );
			break

		# 处理
		print ( buf )

		# Log写入
		if File != None :
			File.write( '[IN] : ' + buf + '\r\n' )
			File.flush()


def Socket_Send( ConnectSocket, ConnectAddr, File ) :
	'''Socket发送函数 循环处理有阻塞 故通常新建线程来执行

	   参数 ConnecSocker : socket句柄
	        ConnectAddr  : 连接端地址
	        File         : Log文件句柄 None则不写入'''

	# 欢迎信息
	ConnectSocket.send( b'welcome to Python-Server!' )

	try :
		while True :
			# 从键盘读入发送信息
			msg = raw_input()
			# 送信
			ConnectSocket.send( msg.encode( 'utf-8' ) )
			# Log
			File.write('[OUT]: ' + msg + '\r\n' )
			File.flush()

	except KeyboardInterrupt :
		# ctrl + c
		print( 'you have Crtl+C, Socket_Send Quit!' )